package net.scribblemedia.sqldsk.service;

import javax.sql.DataSource;

import net.scribblemedia.sqldsk.domain.DatabaseConfig;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.stereotype.Service;

@Service
public class DatabaseConnectionService {

	private static final String PARAM_HOST = "$HOST$";
	private static final String PARAM_DATABASE = "$DATABASE$";
	private static final String PARAM_PORT = "$PORT$";
	
	public DataSource buildDataSource(DatabaseConfig databaseConfig) {
		BasicDataSource ds = new BasicDataSource();
		ds.setDriverClassName(databaseConfig.getDriver().getDriverClass());
		ds.setUsername(databaseConfig.getUsername());
		ds.setPassword(databaseConfig.getPassword());
		ds.setUrl(buildUrl(databaseConfig));
		return ds;
	}

	private String buildUrl(DatabaseConfig databaseConfig) {
		String urlFormat = databaseConfig.getDriver().getUrlFormat();
		String url = urlFormat.replace(PARAM_DATABASE, databaseConfig.getDatabaseName());
		url = url.replace(PARAM_HOST, databaseConfig.getHost());
		url = url.replace(PARAM_PORT, databaseConfig.getPort());
		return url;
	}
}
